<template>
  <e-container :loading="loading">
    <e-title title="Payment Settings" />
    <a-divider />
    <div class="form">
      <a-form ref="formInstance" :model="apiData" layout="vertical" :rules="rules">
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Currency" name="currency">
              <a-select
                v-model:value="currencyWrapper"
                show-search
                option-filter-prop="label"
                option-label-prop="label"
                :get-popup-container="triggerNode => triggerNode.parentNode"
              >
                <a-select-option v-for="item in dict.currencies" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Billing Cycle (Days)" name="payCycle">
              <a-input-number v-model:value="apiData.payCycle" :precision="0" :min="1" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="apiData.payCycle > 45" :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Attachment" name="attachmentName">
              <a-input :value="fileName" :readonly="true">
                <template #addonAfter>
                  <input v-show="false" ref="uploadInput" type="file" @change="uploadFileChange" />
                  <span style="color: #a9b5c9; cursor: pointer" @click="uploadInput.click()">
                    <e-icon type="upload" style="margin-right: 6px" />Upload
                  </span>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-divider />
    <div class="buttons">
      <a-space size="middle">
        <a-button @click="handleCancel">Cancel</a-button>
        <a-button v-permission="'FinancialInformation:BillingCycle:Edit'" type="primary" @click="handleSave">
          Save
        </a-button>
      </a-space>
    </div>
  </e-container>
</template>

<script setup>
import { ref, reactive, inject, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { useDictNullValue } from '@/hooks/useDictNullValue.js'
import { CONFIRM_BACK_TO_DETAIL, SAVED_SUCCESSFULLY, UPLOAD_FAILED } from '@/constants/message'
import financial from '@/api/client/financial.js'
import EContainer from '@/components/EContainer.vue'
import ETitle from '@/components/ETitle.vue'
import EIcon from '@/components/EIcon.vue'
import TargetClient from '@/api/targetClient.js'
const store = useStore()
const route = useRoute()
const router = useRouter()
const emits = defineEmits(['updated'])
const loading = ref(true)
const { id } = route.params
const gutter = [120, 16]
const { Modal, message } = inject('Feedback')
const formInstance = ref(null)
const uploadInput = ref(null)
const dict = ref(computed(() => store.state.dict))
store.dispatch('dict/getCurrencies')
const apiData = reactive({
  id: id,
  currency: 0,
  payCycle: null,
  payCycleAttachID: null,
  attachmentAddr: undefined,
  attachmentName: undefined,
  attachmentFileSize: undefined
})
const currencyWrapper = useDictNullValue(apiData, 'currency')
let apiDataCopy = {}
const rules = computed(() => {
  return {
    payCycle: [
      {
        required: true,
        message: 'Please input billing cycle',
        trigger: 'blur'
      }
    ],
    attachmentName: [
      {
        required: apiData.payCycle > 45,
        message:
          'Because the billing cycle is greater than 45 days, you need to upload file to prove that it has been approved.',
        trigger: 'change'
      }
    ]
  }
})
/**
 * 回显数据
 */
const review = () => {
  financial
    .getPaymentSettings(id)
    .then(({ data }) => {
      apiData.currency = data.currencyID
      apiData.payCycle = data.payCycle
      apiData.payCycleAttachID = data.payCycleAttachID === null ? undefined : data.payCycleAttachID
      apiData.attachmentName = data.attachmentName
      fileName.value = data.attachmentName
      apiDataCopy = JSON.parse(JSON.stringify(apiData))
    })
    .finally(() => {
      loading.value = false
    })
}
const fileName = ref('')
const uploadFileChange = event => {
  if (event.target.files.length > 0) {
    TargetClient.uploadFiles(event.target.files)
      .then(res => {
        if (Array.isArray(res) && res.length > 0 && res[0] instanceof Eci.IO.File) {
          fileName.value = event.target.files.length > 0 ? event.target.files[0].name : ''
          apiData.attachmentAddr = res[0].Path
          apiData.attachmentFileSize = res[0].SourceBaseFileSize
          apiData.attachmentName = fileName.value
          apiData.payCycleAttachID = undefined
          formInstance.value.clearValidate('fileName')
        } else {
          fileName.value = ''
          message.error(UPLOAD_FAILED)
        }
      })
      .catch(() => {
        fileName.value = ''
        uploadInput.value.value = null
        message.error(UPLOAD_FAILED)
      })
  }
}
const handleSave = () => {
  formInstance.value.validate().then(() => {
    if (apiDataCopy.currency !== undefined && apiDataCopy.currency !== apiData.currency) {
      Modal.confirm({
        content:
          "Please note that if the currency is modified, the client's previous negotiated service price will be deleted, sure to do this?",
        okButtonProps: { danger: true },
        okText: 'Yes',
        onOk: () => {
          save()
        }
      })
    } else {
      save()
    }
  })
}
/**
 * 保存
 */
const save = () => {
  financial.updateBillingCycleInfo(apiData).then(res => {
    if (res.code === 2000) {
      message.success(SAVED_SUCCESSFULLY)
      router.push({ name: 'Financial Information' })
      emits('updated')
    }
  })
}
/**
 * 取消模态框
 */
const handleCancel = () => {
  Modal.confirm({
    content: CONFIRM_BACK_TO_DETAIL,
    okButtonProps: { danger: true },
    onOk: () => {
      router.push({ name: 'Financial Information' })
      emits('updated')
    }
  })
}
/**
 * 初始化
 */
onMounted(() => {
  review()
})
</script>

<style scoped lang="less">
.form {
  padding: 0 228px;
}
.buttons {
  text-align: center;
}
.ant-divider {
  border-top: 1px solid #dcdee7 !important;
}
:deep(.ant-input-number-handler-wrap) {
  display: none !important;
}
:deep(.ant-input::-webkit-inner-spin-button),
:deep(.ant-input::-webkit-outer-spin-button) {
  -webkit-appearance: none !important;
  margin: 0;
}
</style>
<route lang="yaml">
name: Payment Settings
path: '/client/:id/financial-information/payment-settings'
meta:
  title: Payment Settings
  permission: FinancialInformation
</route>
